package com.zhxin.nettylab.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;

/**
 * @ClassName HttpClient
 * @Description //HttpClient
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2021/2/25 0025 下午 2:52
 **/
public class HttpClient {

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8088;

        EventLoopGroup group = new NioEventLoopGroup();

        try{

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel channel) throws Exception {

                    ChannelPipeline cp = channel.pipeline();
                    cp.addLast(new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(65536))
                            .addLast(new HttpClientHandler());
                }
            });

            // 启动客户端.
            ChannelFuture f = bootstrap.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
